<?php
/**
 * 
 * @author spring
 * @version 2014-6-7 上午9:12:18
 */
class  Controller_Pandian extends Controller_Admin {
		/**
	 * 
	 * Description
	 *  库存盘点查询与下载
	 */
	
    public function before()
    {
    	try {
    		  ACL::Required('pandian');
    	} catch ( HTTP_Exception_403 $e ) {
				Message::error('sorry，你没有权限进这个目录');
    		$this->request->redirect ( URL::base (true) );
    	}
        parent::before();
    }
	/**
	 * 
	 * Description
	 *  库存盘点，可以查询任意时刻的库存量
	 */
	public function action_index()
 	{
 		$this->title='盘点库存';
 		$content=View::factory("delivery/pandian");
 		$this->response->body($content);
 	}
 	
 	/**
 	 *
 	 * Description
 	 *  库存盘点界面的ajax查询控制器，根据查询条件查出结果，因为每天的出入库记录很多，这里分页数目到真实环境再考虑
 	 */
 	public function action_search()
 	{
 		$tablename='inventories';
 		$result=$this->fenye($tablename);
 		$view=View::factory('delivery/pandian_table')->set('num', $result['num'])->set('datas',self::be($result['datas']))->bind('pager_links', $result['pager_links'])->render();
        echo $view;

 	}

    //借料添加
    public function be ($arrs = NULL) {
        if(!empty($arrs)) {
            $skus = array();
            foreach($arrs as $v) {
                $skus[] = strtoupper($v['sku']);
            }
            $lends = checkstock::getLendsNums($skus);
            foreach($arrs as &$v) {
                $v['lend'] = isset($lends[$v['sku']]) ? $lends[$v['sku']] : 0;
            }
        }
        return $arrs;
    }
 	
 	
 	/**
 	 *
 	 * Description
 	 *盘点记录查询界面
 	 */
 	public function action_pandian_search(){
 			
 		$this->title='盘点记录查询';
 		$content=View::factory("delivery/pandian_search");
 		$this->response->body($content);
 	}
 	/**
 	 *
 	 * Description
 	 * ajxa 执行盘点记录搜索
 	 */
 	public function action_pandian_searchto()
 	{
 		$tablename='pandians';
 		$condition=$_GET;
 		$condition['items_per_page']=20;
 		$result=$this->fenye2($tablename,$condition);
 		$view=View::factory('delivery/pandian_search_table')->set('datas',$result['datas'])->bind('pager_links', $result['pager_links'])->render();
 		echo $view;
 	
 	}
 	
 	/**
 	 *
 	 * Description
 	 *  下载固定页数的盘点库存数据
 	 */
 	public function action_down()
 	{
 		set_time_limit(0);
 		$condition=$_GET;
 		$tablename='inventories';
 		//ini_set('memory_limit','512M');
        ini_set('memory_limit','2048M');
 		require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
 		$this->objReader  = PHPExcel_IOFactory::createReader('Excel5');
 		$objPHPExcel      = new PHPExcel();
 		$objPHPExcel->getProperties()->setCreator("YKS")
 		->setLastModifiedBy("YKS")
 		->setTitle("Office 2003 XLSX Test Document")
 		->setSubject("Office 2003 XLSX Test Document")
 		->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
 		->setKeywords("office 2003 openxml php")
 		->setCategory("Test result file");
 		$objActSheet =$objPHPExcel->setActiveSheetIndex(0);
 		$objActSheet->setCellValue('A1', 'SKU');
 		$objActSheet->setCellValue('B1', '单据下载时间');
 		$objActSheet->setCellValue('C1', '品名');
 		$objActSheet->setCellValue('D1', '储位');
 		$objActSheet->setCellValue('E1', '库存量');
 		$objActSheet->setCellValue('F1', '盘点时间（xxxx-xx-xx）');
 		$objActSheet->setCellValue('G1', '实际盘点量');
        $objActSheet->setCellValue('H1', '借料备注量');
 		$pre= Pandian::getListInfoCondition(Pandian::getListPre($tablename),$condition,true,$tablename);
 		$datas=$pre->execute('newerp')->as_array();
 		//$datas=Pandian::getList($items_per_page,$offset,$pre);
 	    $datas=self::be(Pandian::excute_data_new($datas,$condition['start_time']));

 	    $time=date('Y-m-d H:i:s');
 		for($i=0;$i<count($datas);$i++)
 		{
 		$key=$i+2;
 		$objActSheet->setCellValue('A'.$key, $datas[$i]['sku']);
 		$objActSheet->setCellValue('B'.$key, $time);
 		$objActSheet->setCellValue('C'.$key, $datas[$i]['sku_name']);
		$objActSheet->setCellValue('D'.$key, $datas[$i]['storage_position']);
 		$objActSheet->setCellValue('E'.$key, $datas[$i]['quantity']);
 		$objActSheet->setCellValue('F'.$key, date('Y-m-d'));
        $objActSheet->setCellValue('H'.$key, $datas[$i]['lend']);
 		}
 		$objPHPExcel->getActiveSheet()->setTitle('盘点报表');
		$objPHPExcel->setActiveSheetIndex(0);
 		$day=date("m-d");
 		$filename=$day.'盘点报表'.'.xls';
        ob_end_clean();
		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
		header('Content-Disposition: attachment;filename='.$filename);
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
 	}
	
//  	/**
//  	 *
//  	 * Description
//  	 *  下载固定页数的盘点库存数据
//  	 */
//  	public function action_down()
//  	{
//  		$condition=$_GET;
//  		$tablename='inventories';
//  		$items_per_page=0;
//  		if(isset($_GET['per_page'])&&!empty($_GET['per_page']))
//  		{
//  			$items_per_page=$_GET['per_page'];
//  		}else {
//  			$items_per_page=15;
//  		}
//  		if(isset($_GET['page'])&&!empty($_GET['page']))
//  		{
//  			$page=$_GET['page'];
//  			$offset=($_GET['page']-1)*$items_per_page;
//  		}else {
//  			$page=1;
//  			$offset=0;
//  		}
//  		set_time_limit(0);
//  		ini_set('memory_limit','512M');
//  		require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
//  		$this->objReader  = PHPExcel_IOFactory::createReader('Excel5');
//  		$objPHPExcel      = new PHPExcel();
//  		$objPHPExcel->getProperties()->setCreator("ROMWE")
//  		->setLastModifiedBy("ROMWE")
//  		->setTitle("Office 2003 XLSX Test Document")
//  		->setSubject("Office 2003 XLSX Test Document")
//  		->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
//  		->setKeywords("office 2003 openxml php")
//  		->setCategory("Test result file");
//  		$objActSheet =$objPHPExcel->setActiveSheetIndex(0);
//  		$objActSheet->setCellValue('A1', 'SKU');
//  		$objActSheet->setCellValue('B1', '单据下载时间');
//  		$objActSheet->setCellValue('C1', '品名');
//  		$objActSheet->setCellValue('D1', '储位');
//  		$objActSheet->setCellValue('E1', '规格');
//  		$objActSheet->setCellValue('F1', '库存量');
//  		$objActSheet->setCellValue('G1', '实际盘点量');
//  		$pre= Pandian::getListInfoCondition(Pandian::getListPre($tablename),$condition,true,$tablename);
//  		$datas=Pandian::getList($items_per_page,$offset,$pre);
//  		$datas=Pandian::excute_data($datas,$condition['start_time']);
//  		$time=date('Y-m-d H:i:s');
//  		for($i=0;$i<count($datas);$i++)
//  		{
//  		$key=$i+2;
//  		$objActSheet->setCellValue('A'.$key, $datas[$i]['sku']);
//  				$objActSheet->setCellValue('B'.$key, $time);
//  				$objActSheet->setCellValue('C'.$key, $datas[$i]['sku_name']);
//  						$objActSheet->setCellValue('D'.$key, $datas[$i]['storage_position']);
//  						$objActSheet->setCellValue('E'.$key, $datas[$i]['sku_standard']);
//  						$objActSheet->setCellValue('F'.$key, $datas[$i]['quantity']);
 							
//  		}
//  		$objPHPExcel->getActiveSheet()->setTitle('盘点报表');
//  		$objPHPExcel->setActiveSheetIndex(0);
//  		$day=date("m-d");
//  		$filename=$day.'盘点报表page'.$page.'.xls';
//  		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
//  		header('Content-Disposition: attachment;filename='.$filename);
//  		header('Cache-Control: max-age=0');
//  		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//  		$objWriter->save('php://output');
//  		exit;
//  	}
 	
 	/**
 	 * 
 	 * Description
 	 * 库存盘点上传模版下载
 	 */
 	public function action_down_template()
 	{
 		$this->title='下载模版';
 		require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
 		$this->objReader  = PHPExcel_IOFactory::createReader('Excel5');
 		$objPHPExcel      = new PHPExcel();
 		$objPHPExcel->getProperties()->setCreator("newerp")
 		->setLastModifiedBy("newerp")
 		->setTitle("Office 2003 XLSX Test Document")
 		->setSubject("Office 2003 XLSX Test Document")
 		->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
 		->setKeywords("office 2003 openxml php")
 		->setCategory("Test result file");
 		$objActSheet =$objPHPExcel->setActiveSheetIndex(0);
 		$objActSheet->setCellValue('A1', 'SKU');
 		$objActSheet->setCellValue('B1', '盘点库存量');
 		$objPHPExcel->getActiveSheet()->setTitle('');
 		$objPHPExcel->setActiveSheetIndex(0);
 		$day=date("m-d");
        ob_end_clean();
 		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
 		header('Content-Disposition: attachment;filename="'.$day.'库存盘点上传模版.xls"');
 		header('Cache-Control: max-age=0');
 		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
 		$objWriter->save('php://output');
 		exit;
 	}
 	
 	/**
 	 *
 	 * Description
 	 * 库存盘点上传
 	 */
 	public function action_upload_pandian()
 	{
		set_time_limit(0);
 	    $this->title='盘点单';
 	    $time=date('Y-m-d H:i:s');
 	    if(isset($_GET['page'])&&$_GET['page']>1){
			$sql="select op_time from pandians order by op_time desc limit 1";
			$date=DB::query(Database::SELECT,$sql)->execute('newerp')->current();
			if(isset($date['op_time'])){
				$time=$date['op_time'];
			} 	    	
 	    }
	 	ini_set('memory_limit','500M');
	 	require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
	 	$xls= $_FILES['xls']['tmp_name'];
	 	if($xls){
	 	$objPHPExcel= PHPExcel_IOFactory::load($xls);
	 	$data= $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
	 	Pandian::check_pandian_upload($data);
	 	$lines=Pandian::do_pandian_upload($data,$time);
	 	}
	 	$tablename='pandians';
	 	$result=$this->fenye2($tablename,$condition=array('time'=>$time,'items_per_page'=>10));
	 	$view=View::factory('delivery/special_upload_result2')->set('datas',$result['datas'])->set('pager_links', $result['pager_links'])
	 	->set('lines',$lines);
	 	$this->response->body($view);
 	}
 	

 	/**
 	 * 
 	 * Description 一个简单的封装用来分页
 	 * @param field_type  bare_field_name
 	 * @param string $tablename
 	 * @return array  返回分页数据和视图 
 	 */
 	private function fenye($tablename)
 	{
        //$condition 是查询条件
        $condition=$_GET;
        if(isset($_GET['supplier'])&&!empty($_GET['supplier']))
        {
            $condition['supplier']=Pandian::getidByName($condition['supplier']);
        }
        //根据前台传来的自定义页数来分页
        if(isset($_GET['per_page'])&&!empty($_GET['per_page']))
        {
            $items_per_page=$_GET['per_page'];
        }else {
            $items_per_page=15;
        }
        $pre= Pandian::getListInfoCondition(Pandian::getTotlePre($tablename),$condition,false,$tablename);
        $num = Pandian::getTotle($pre);
        $pagination = Pagination::factory(array(
                'total_items' =>$num,
                'view' => 'pagination/ajax_basic',
                'items_per_page' => $items_per_page,
                'uri'=>$this->request->uri(),
        ));
        if(isset($_GET['page'])&&!empty($_GET['page']))
        {
            $offset=($_GET['page']-1)*$items_per_page;
        }else {
            $offset=0;
        }
        $pre= Pandian::getListInfoCondition(Pandian::getListPre($tablename),$condition,true,$tablename);
        $datas=Pandian::getList($items_per_page,$offset,$pre);
        $datas=Pandian::excute_data($datas,$condition['start_time']);
        $pager_links = $pagination->render();
        $result=array('datas'=>$datas,'pager_links'=>$pager_links,'num'=>$num);
        return $result;
 	}





 	private function fenye2($tablename,$condition)
 	{ 
    	$items_per_page=$condition['items_per_page'];
 		$pre=Pandianinout::getListInfoCondition(Pandianinout::getTotlePre($tablename),$condition,false,$tablename);
 		$pagination = Pagination::factory(array(
 				'total_items' =>Pandian::getTotle($pre),
 				'view' => 'pagination/ajax_basic',
 				'items_per_page' => $items_per_page,
 				'uri'=>$this->request->uri(),
 		));
 		if(isset($_GET['page'])&&!empty($_GET['page']))
 		{
 			$offset=($_GET['page']-1)*$items_per_page;
 		}else {
 			$offset=0;
 		}
 		$pre= Pandianinout::getListInfoCondition(Pandianinout::getListPre($tablename),$condition,true,$tablename);
 		$datas=Pandianinout::getList($items_per_page,$offset,$pre);
 		$pager_links = $pagination->render();
 		$result=array('datas'=>$datas,'pager_links'=>$pager_links);
 		return $result;
 	}
}
